<?php
ini_set('error_reporting', E_ALL);

$id = $_GET['id'];

require_once '../libs/contest_db.php';
$dbConfig = include '../dbconfig.php';
$db = new contest_db($dbConfig);
$info = $db->getRow("SELECT * FROM st_ap_forms WHERE form_id = ".intval($id), true);
die("call me");
include("PFBC/Form.php");

$form = new PFBC\Form("elements", 400);
$form->addElement(new PFBC\Element\Hidden("form", $id));
$form->addElement(new PFBC\Element\Hidden("name", $info->form_name));
$form->addElement(new PFBC\Element\Hidden("email", $info->form_email));
$form->addElement(new PFBC\Element\Hidden("success",$info->form_success_message));
$result = $db->getRows("SELECT * FROM st_ap_form_elements WHERE form_id=".intval($info->form_id)." ORDER BY element_sort,element_id", true);

$height = array('large'=>'width:408px;height:20em; border:1px solid #CCC;','medium'=>'width:408px;height:10em; border:1px solid #CCC;','small'=>'width:408px;height:5.5em; border:1px solid #CCC;');
$width = array('large'=>'width:408px; border:1px solid #CCC;','medium'=>'width:408px; border:1px solid #CCC;','small'=>'width:120px; border:1px solid #CCC;');
$stt  = 4;
foreach($result as $row){
    switch($row->element_type){
        case 'text':
            {
                $form->addElement(new PFBC\Element\Textbox($row->element_title.":", $row->element_id,array(
	"value" => $row->element_default_value,"required"=>$row->element_is_required,"title"=>$row->element_guidelines),$row->element_size));
                break;
            }
            case 'break':
            {
                $form->addElement(new PFBC\Element\Section($row->element_title, $row->element_id,array(
	"value" => $row->element_default_value,"required"=>$row->element_is_required,"hr"=>$row->element_horizontal),$width[$row->element_size]));
                break;
            }
        case 'textarea':
            {
                $form->addElement(new PFBC\Element\Textarea($row->element_title.":", $row->element_id,array(
	"value" => $row->element_default_value,"required"=>$row->element_is_required,"title"=>$row->element_guidelines),$row->element_size));
                break;
            }
        case 'radio':
            {
                foreach($db->getRows("SELECT * FROM st_ap_element_options WHERE form_id = ".intval($id)." AND element_id = ".$row->element_id, true) as $option){
                    $options[] = $option->option;
                    if($option->option_is_default == 1)
                            $default = $option->option;
                }
                $form->addElement(new PFBC\Element\Radio($row->element_title.":", $row->element_id, $options,array(
                "value" => $default,"required"=>$row->element_is_required,"title"=>$row->element_guidelines)));
                $default = '';
                $options = array();
                break;
                
            }
        case 'checkbox':
        {
                foreach($db->getRows("SELECT * FROM st_ap_element_options WHERE form_id = ".intval($id)." AND element_id = ".$row->element_id, true) as $option){
                    $options[] = $option->option;
                    if($option->option_is_default == 1)
                            $default = $option->option;
                }
                $form->addElement(new PFBC\Element\Checkbox($row->element_title.":", $row->element_id, $options,array(
                "value" => $default,"required"=>$row->element_is_required,"title"=>$row->element_guidelines)));
                $default = '';
                $options = array();
                break;
        }
        case 'select':
        {
                foreach($db->getRows("SELECT * FROM st_ap_element_options WHERE form_id = ".intval($id)." AND element_id = ".$row->element_id, true) as $option){
                    $options[] = $option->option;
                    if($option->option_is_default == 1)
                            $default = $option->option;
                }
                $form->addElement(new PFBC\Element\Select($row->element_title.":", $row->element_id, $options,array(
                "value" => $default,"required"=>$row->element_is_required,"title"=>$row->element_guidelines),$row->element_size));
                $default = '';
                $options = array();
                break;
        }
        case 'option':{
            foreach($db->getRows("SELECT * FROM st_ap_element_matrix WHERE form_id = ".intval($id)." AND element_id = ".$row->element_id, true) as $option){
                    $matrix_column[] = $option->option_column;
                    $matrix_row[] = $option->option_row;
                }
                $options['column'] = $matrix_column;
                $options['row'] = $matrix_row;
                $form->addElement(new PFBC\Element\Matrix($row->element_title.":", $row->element_id, $options,array("required"=>$row->element_is_required,"title"=>$row->element_guidelines),null,1));
                $options = array();
                break;
        }
}
if($row->element_is_required == 1){
    $required[] =  'elements-element-'.$stt.':'.$row->element_type.':'.$row->element_title;
}
$stt++;
}
?>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <head>
        <title><?php echo $info->form_name;?></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
<body>

<div style="display:none;margin:0 auto;" class="w538">
    <div class="w508">
        <?php
        $style = '';
        if($info->title_color != ''){
            $style = 'color:'.$info->title_color;
        }
        ?>
    	<h1 class="t_ogran" style="<?php echo $style;?>;<?php if(intval($info->title_font_size) > 0){?>font-size:<?php echo $info->title_font_size;?><?php }?>"><?php echo nl2br($info->form_name);?>
</h1>
        <p class="t_gray" style="line-height:14px;color:<?php echo $info->text_color_setting;?>"><?php echo nl2br($info->form_description);?>

</p>
<div id="error" style="display:none;"></div>
<input type="hidden" id="required" value="<?php echo implode(',',$required);?>" />
<?php
$form->render();
?>
</div>
</div>
<style>

    #elements .pfbc-element {
        border-bottom: none;
    }
    #elements .pfbc-label label {
        font-weight: lighter;
    }
    .form_description {
        margin:0 auto;
        width:490px; padding:0px;
}
    .form_description h2 {
        color:#F00; 
        font-size:26px; 
        padding:0px;
        margin:0px;
    }
    #elements .pfbc-buttons  {
        text-align: left;
    }
    input.ui-button {
    padding: 3px;
    }
</style>
    <link rel="stylesheet" type="text/css" href="styles/style_1.css">
    <?php if(intval($info->form_style) > 0){?>
<!--    <link rel="stylesheet" type="text/css" href="styles/style_<?php echo $info->form_style;?>.css">-->
    <?php }
    else {?>
<!--     <link rel="stylesheet" type="text/css" href="styles/style_0.css">-->
    <?php }?>
<script type="text/javascript">
function check_form(){
    jQuery("#error").hide();
    jQuery("#error").html('');
    var string = jQuery("#required").val();
    var array = string.split(',');
    var check = true;
    jQuery.each(array,function(index,value){
       if(value.split(':')[1] == 'text' || value.split(':')[1] == 'textarea'){
           if(jQuery('#'+value.split(':')[0]).val() == ''){
            jQuery("#error").append("Please input "+value.split(':')[2]+"<br />");
            jQuery('#'+value.split(':')[0]).parent().attr('style','background:#FFF7C0');
          }
          else {
              jQuery('#'+value.split(':')[0]).parent().removeAttr('style');
          }
       }
       else {
           
           if(value.split(':')[1] == 'radio' || value.split(':')[1] == 'checkbox'){
               check = false;
               for(var i = 0;i<jQuery("#"+value.split(':')[0]+" tr").length;i++){
                   if(jQuery("#"+value.split(':')[0]+"-"+i+":checked").val() == jQuery("#"+value.split(':')[0]+"-"+i).val()){
                       check = true;
                   }
               }
               if(!check){
                    jQuery("#error").append("Please choose "+value.split(':')[2]+"<br />");
                    jQuery('#'+value.split(':')[0]).parent().attr('style','background:#FFF7C0');
               }
               else{
                   jQuery('#'+value.split(':')[0]).parent().removeAttr('style');
               }
           }
           else {
               if(value.split(':')[1] == 'matrix'){
                   check = false;
                   for(var i = 0;i<jQuery("#"+value.split(':')[0]+" tr").length;i++){
                       if(jQuery("#"+value.split(':')[0]+"-"+i+":checked").val() == jQuery("#"+value.split(':')[0]+"-"+i).val()){
                           check = true;
                       }
                   }
                   if(!check){
                        jQuery("#error").append("Please choose "+value.split(':')[2]+"<br />");
                        jQuery('#'+value.split(':')[0]).parent().attr('style','background:#FFF7C0');
                   }
                   else {
                       jQuery('#'+value.split(':')[0]).parent().removeAttr('style');
                   }
               }
           }
       }
       
    });
    if(jQuery("#error").html() == ''){
        var data = new Array();
        jQuery.each(jQuery(".pfbc-element"),function(index,value){
        if(index < (jQuery(".pfbc-element").length - 1)){
            var stt = index+4;
         if(jQuery("#elements-element-"+stt).attr('type') == 'text' || jQuery("#elements-element-"+stt).attr('class') == 'pfbc-textarea width_medium vtip' || jQuery("#elements-element-"+stt).attr('class') == 'pfbc-textarea width_medium '){
            //alert(jQuery("#elements-element-"+stt).val());
            if(jQuery("#elements-element-"+stt).val() != '')
                data[jQuery("#elements-element-"+stt).attr('name')] =  jQuery("#elements-element-"+stt).val();
            }
            else {
                if(jQuery("#elements-element-"+stt+" div").attr('class') == 'pfbc-radio-buttons'){
                    var max = jQuery("#elements-element-"+stt+" .pfbc-radio-buttons .pfbc-radio").length - 1;
                    var string = '';
                    for(var i=0;i<=max;i++){
                        if(jQuery("#elements-element-"+stt+"-"+i).attr('checked')){
                            string = jQuery("#elements-element-"+stt+"-"+i).val();
                            var name = jQuery("#elements-element-"+stt+"-"+i).attr('name');
                        }
                    }
                    //alert(string);
                    if(string != '')
                        data[name] = string;
                }
                else {
                     if(jQuery("#elements-element-"+stt+" div").attr('class') == 'pfbc-checkboxes'){
                         var max = jQuery("#elements-element-"+stt+" .pfbc-checkboxes .pfbc-checkbox").length - 1;
                         var string = '';
                         for(var i=0;i<=max;i++){
                            if(jQuery("#elements-element-"+stt+"-"+i).attr('checked')){
                                if(string != ''){
                                    string = string + ',';
                                    
                                    
                                    
                                }
                                string = string + jQuery("#elements-element-"+stt+"-"+i).val();
                                var name = stt - 3;
                            }
                        }
                       // alert(string);
                       if(string != '')
                        data[name.toString()] = string;
                     }
                     else {
                         if(jQuery("#elements-element-"+stt).attr('class') == 'pfbc-select width_medium'){
                             //alert(jQuery("#elements-element-"+stt).val());
                             data[jQuery("#elements-element-"+stt).attr('name')] = jQuery("#elements-element-"+stt).val();
                         }
                         else {
                             if(jQuery("#elements-element-"+stt).attr('cellspacing') == '5'){
                                   var string = '';
                                 jQuery.each(jQuery("#elements-element-"+stt+" tr[align='center']"),function(index2,value2){
                                     var number = index2+1;
                                     var stt2 = stt-3;
                                     jQuery.each(jQuery("input[name='"+stt2+"["+number+"]']"),function(index3,value3){
                                        if(value3.checked){
                                            if(string != ''){
                                            string = string + ',';
                                            }
                                            string = string + value3.value;
                                        }
                                       
                                     });
                                      
                                       //string = string + jQuery("input[name='"+stt2+"["+number+"]']").val();
                                 });
                                 name = stt - 3;
                                 if(string != '')
                                    data[name.toString()] = string;
                             }
                         }
                     }
                    
                }
            }
        }
        });
        var json = '{';
        for(i in data){
            if(json != '{'){
            json = json+',';
            }
            json = json + '"'+i+'":"'+data[i]+'"';
        }
        json  = json + ',"recaptcha_response_field":"'+jQuery("#recaptcha_response_field").val()+'","recaptcha_challenge_field":"'+jQuery('#recaptcha_challenge_field').val()+'"';
        json = json + '}';
       jQuery.post("index.php",{value:json,form:"<?php echo $id;?>",name:"<?php echo $info->form_name;?>",email:"<?php echo $info->form_email;?>",success:"<?php echo $info->form_success_message;?>"},function(data2){
           if(data2 == '0'){
               $( "#dialog-modal2" ).dialog({
			height: 140,
                        width:300,
			modal: true,
                        position:['center',100]
                    });
                    Recaptcha.reload ();
           }
           else 
               {
                   $( "#dialog-modal" ).dialog({
			height: 140,
                        width:300,
			modal: true,
                        position:['center',100]
                    });
                    Recaptcha.reload ();
               }
       })
        return false;
    }
    else{
       //jQuery("#error").slideDown();
       return false; 
    }
    
}
//jQuery("#elements").attr("onsubmit","alert('hehe');");
//jQuery("#elements").attr("onsubmit","return check_form();");
//jQuery("#elements").attr("name","form_name");
</script>

<script type="text/javascript" src="tooltip/vtip.js"></script>
<link rel="stylesheet" type="text/css" href="tooltip/css/vtip.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Playfair+Display|Limelight|Maven+Pro|Muli|Tenor+Sans|Brawler|Carter+One|Wire+One|Nunito|Podkova|The+Girl+Next+Door|Ruslan+Display|Jura|Caudex|Waiting+for+the+Sunrise|Shanti|Metrophobic|Play|Rokkitt|Ultra|Wallpoet|Paytone+One|Francois+One|Didact+Gothic|Judson|Mako|Sigmar+One|Megrim|Holtwood+One+SC|Over+the+Rainbow|Monofett|News+Cycle|Bigshot+One|Smythe|Special+Elite|Miltonian|Kreon|Open+Sans|Oswald|Vibur|Nova|Michroma|Indie+Flower|Meddon|Droid+Sans+Mono|Pacifico|Quattrocento+Sans|Amaranth|Annie+Use+Your+Telescope|Bangers|Coming+Soon|Expletus+Sans|Terminal+Dosis+Light|UnifrakturCook|Tangerine|MedievalSharp|Sniglet|Dancing+Script|Astloch|Cabin+Sketch|Quattrocento|Sunshiney|Kenia|Chewy|Old+Standard+TT|Calligraffitti|Arvo|PT+Serif|Anton|Orbitron|Schoolbell|PT+Sans|Corben|IM+Fell|Just+Another+Hand|Architects+Daughter|Rock+Salt|UnifrakturMaguntia|Syncopate|Goudy+Bookletter+1911|Bentham|Puritan|Irish+Grover|Crafty+Girls|Cherry+Cream+Soda|Permanent+Marker|Radley|Allerta|Kristi|League+Script|Crushed|Kranky|Neuton|Yanone+Kaffeesatz|Vollkorn|Maiden+Orange|Neucha|Reenie+Beanie|Slackey|Homemade+Apple|Cousine|Lekton|Arimo|Josefin+Sans|Mountains+of+Christmas|Luckiest+Guy|Copse|Droid+Serif|Cardo|Geo|Cantarell|Raleway|Gruppo|Allerta+Stencil|EB+Garamond|Unkempt|Cuprum|Ubuntu|Droid+Sans|Dawning+of+a+New+Day|Molengo|Lobster|Anonymous+Pro|Merriweather|Six+Caps|Nobile|Inconsolata|Allan|Cabin|Covered+By+Your+Grace|OFL+Sorts+Mill+Goudy+TT|Tinos|Josefin+Slab|Bevan|Philosopher|Buda|Lato|Damion|Fontdiner+Swanky|Coda|Sue+Ellen+Francisco|Crimson+Text|VT323|Aclonica|Candal|Walter+Turncoat|Just+Me+Again+Down+Here|Swanky+and+Moo+Moo" />
<style>
    .w538 {
       <?php if($info->background_color_setting != ''){?> background-color:<?php echo $info->background_color_setting;?>;<?php }?>
         <?php if($info->text_color_setting != ''){?>color:<?php echo $info->text_color_setting;?><?php }?>
    }
    label {
        <?php if($info->text_color_setting != ''){?>color:<?php echo $info->text_color_setting;?>;<?php }?>
    }
    #elements td label,#elements td {
        <?php if($info->text_color_setting != ''){?>color:<?php echo $info->text_color_setting;?>;<?php }?>
        <?php if($info->font_type != ''){?>font-family: '<?php echo $info->font_type; ?>', serif;<?php }?>
        <?php if(intval($info->text_font_size) > 0){?>font-size:<?php echo $info->text_font_size;?>px;<?php }?>
    }
    hr {
        <?php if($info->text_color_setting != ''){?>color:<?php echo $info->text_color_setting;?>;
        border-color:<?php echo $info->text_color_setting;?>;
        <?php }?>
    }
    
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
     <?php if($info->submit_button_color != ''){?>background: none repeat-x scroll 50% 50% <?php echo $info->submit_button_color;?>;<?php }?>
    <?php if($info->submit_button_text_color != ''){?> color: <?php echo $info->submit_button_text_color;?>;<?php }?>
    font-weight: bold;
    <?php if(intval($info->submit_font_size) > 0){?>font-size:<?php echo $info->submit_font_size;?>px;<?php }?>
}
    html {
<?php if($info->font_type != ''){?>font-family: '<?php echo $info->font_type; ?>', serif;<?php }?>
        <?php if(intval($info->text_font_size) > 0){?>font-size:<?php echo $info->text_font_size;?>px;<?php }?>
        <?php if($info->text_color_setting != ''){?>color:<?php echo $info->text_color_setting;?><?php }?>
}
input.ui-button {
    <?php if($info->font_type != ''){?>font-family: '<?php echo $info->font_type; ?>', serif;<?php }?>
}
</style>
<script type="text/javascript">
    jQuery(".w538").attr('style','display:block;margin-left:auto;margin-right:auto;');
    jQuery( "#dialog:ui-dialog" ).dialog( "destroy" );
</script>
<div style="display:none">
<div id="dialog-modal" title="">
	<p><?php echo $info->form_success_message;?></p>
</div>
<div id="dialog-modal2" title="">
	<p>Captcha error</p>
</div>
</div>
</body>
</html> 